package com.lvfeng.tool;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 网络连接相关工具类
 */
public class NetTool {
    public static final String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static final String DEF_CHATSET = "UTF-8";

    /**
     * 创建Http连接并调用接口数据
     */
    public static String getNetData(String strUrl, Map param, String method) throws Exception{
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String res = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(null == method || "GET".equals(method)){
                strUrl = strUrl + "?" + urlEncode(param);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(null == method || "GET".equals(method)){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent",userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (null != param && "POST".equals(method)){
                try {
                    DataOutputStream dos =new DataOutputStream(conn.getOutputStream());
                    dos.writeBytes(urlEncode(param));
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while (null != (strRead = reader.readLine())){
                sb.append(strRead);
            }
            res = sb.toString();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (null != reader){
                reader.close();
            }
            if (null != conn){
                conn.disconnect();
            }
        }
        return res;
    }

    /**
     * 转码
     */
    public static String urlEncode(Map<String,Object>data){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
